// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/

// See page 16.
//!+

// Fetch prints the content found at each specified URL.
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

func main() {
	for _, url := range os.Args[1:] {
		resp, err := http.Get(url)
		if err != nil {
			fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
			os.Exit(1)
		}
		b, err := ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
			os.Exit(1)
		}
		fmt.Printf("%s", b)
	}
}

//!-

// EXE 1.7 用io.Copy替代ioutil.ReadAll，io.Copy结果保存在err里，确保检查了err
// EXE 1.8 处理os.Args[1:]里的url不包含协议的情况，按照https处理
//package main

//import (
//	"fmt"
//	"io"
//	"net/http"
//	"os"
//	"strings"
//)
//
//func main()  {
//	for _, url := range os.Args[1:] {
//		if ! (strings.HasPrefix("http", url) || strings.HasPrefix("https", url)) {
//			url = "https://" + url
//		}
//		resp, err := http.Get(url)
//		if err != nil {
//			fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
//			os.Exit(1)
//		}
//		if _, err = io.Copy(os.Stdout, strings.NewReader(fmt.Sprintf("%s\n", resp.Status))); err != nil {
//			fmt.Fprintf(os.Stderr, "respose: %v\n", err)
//		}
//	}
//}
